//
//  Controller18.swift
//  Swift30Days
//
//  Created by licheng ke on 2017/3/10.
//  Copyright © 2017年 licheng ke. All rights reserved.
//

import UIKit

// LimitCharactors
class Controller18: UIViewController , UITextViewDelegate{

    var isShowBar : Bool = false {
        willSet{
            self.navigationController?.setNavigationBarHidden(newValue, animated: true);
        }
    }
    
    @IBOutlet weak var toolBar: UIToolbar!
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var labelItem: UIBarButtonItem!
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(upKeyBoard(noti:)), name: Notification.Name.UIKeyboardWillShow, object: nil);
        NotificationCenter.default.addObserver(self, selector: #selector(downKeyBoard(noti:)), name: Notification.Name.UIKeyboardWillHide, object: nil);
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated);
        self.isShowBar = false;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let length = textView.text.characters.count;
        if length + range.length > 50 {
            return false;
        }
        return true;
    }
    
    func textViewDidChange(_ textView: UITextView) {
        let count = 50 - textView.text.characters.count
        self.labelItem.title = "\(count)"
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
        self.isShowBar = !isShowBar;
    }
    
    func upKeyBoard(noti : Notification){
        let info = noti.userInfo!;
        let height = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height;
        var frame = self.toolBar.frame;
        frame.origin.y -= CGFloat(height)
        self.toolBar.frame = frame;
    }
    
    func downKeyBoard(noti : Notification){
        var frame = self.toolBar.frame;
        frame.origin.y = SCREEN_H - self.toolBar.frame.height;
        self.toolBar.frame = frame;
    }
    
    
}
